#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : 2021/3/30 22:18 
# @Author : wenzi
# @File : api_user.py
# @Software: PyCharm
import time
import json

from apiRestful.extensions import db
from flask_restful import Api
from flask import jsonify, request
from . import api_bp
from apiRestful.models.user import User
from apiRestful.api.api_auth import generator_auth_token
from apiRestful.utils import log_util
from apiRestful.utils.cors_utils import TabrResource

api_user = Api(api_bp)
logger = log_util.log


class UserAddApi(TabrResource):
    def post(self):
        logger.debug('UserAddApi.post.url = ' + str(request.url))
        raw_data = request.get_data(as_text=True)
        user_info = json.loads(raw_data)
        logger.debug('UserAddApi.post.user_info = ' + str(user_info))
        if not all([user_info['username'], user_info['password'], user_info['password2'], user_info['email']]):
            reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} User add: Miss require params!'
            response = jsonify({'msg': reason, 'error_code': 10001})
        elif user_info['password'] != user_info['password2']:
            reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} User add: Twice input password must be consistent!'
            response = jsonify({'msg': reason, 'error_code': 10002})
        else:
            u = User.query.filter_by(username=user_info['username']).first()
            if u is None:
                try:
                    u = User(username=user_info['username'])
                    u.password = user_info['password']
                    u.email = user_info['email']
                    db.session.add(u)
                    db.session.commit()
                except Exception as e:
                    logger.error(e)
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} User add: {user_info["username"]} failure...'
                    db.session.rollback()
                    response = jsonify({'msg': reason, 'error_code': 10009})
                else:
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} User add: {user_info["username"]} success...'
                    response = jsonify({'msg': reason, 'error_code': 0})
                finally:
                    db.session.close()
            else:
                reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} User add: {user_info["username"]} failure,because username has used....'
                db.session.rollback()
                response = jsonify({'msg': reason, 'error_code': 10003})
        logger.debug('UserAddApi.post.response = ' + response.get_data(as_text=True))
        return response


class UserVerifyApi(TabrResource):
    def post(self):
        logger.debug('UserVerifyApi.post.url = ' + str(request.url))
        raw_data = request.get_data(as_text=True)
        user_info = json.loads(raw_data)
        try:
            u = User.query.filter_by(username=user_info['username']).first()
            if u is None or u.verify_password(user_info['password']) is False:
                reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} User query: {user_info["username"]} failure...'
                response = jsonify({'msg': reason, 'error_code': 10005})
            else:
                logger.debug(f'{time.strftime("%Y-%m-%d %H:%M:%S")} User query: {user_info["username"]} success...')
                token = generator_auth_token(u)
                response = jsonify({'token': token.decode('ascii'), 'error_code': 0})
        except:
            reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} User query: {user_info["username"]} failure...'
            response = jsonify({'msg': reason, 'error_code': 10009})
        finally:
            db.session.close()
            logger.debug('UserVerifyApi.post.response = ' + response.get_data(as_text=True))
            return response


api_user.add_resource(UserAddApi, '/useradd', endpoint='useradd')
api_user.add_resource(UserVerifyApi, '/userverify', endpoint='userverify')
